import { memo, useEffect } from "react";
import { Link } from "react-router-dom";
import { Button } from "antd";
import Errors from "../../components/Errors";
import { useDispatch, useSelector } from "react-redux";
import {
  loginFileUpdate,
  loginSubmit,
  onUnload,
} from "../../store/module/loginSlice";
import request from "../../request";
import { useNavigate } from "react-router-dom";

const Login = () => {
  // 从 Redux store 获取登录相关状态
  let { email, password, errors } = useSelector((state) => {
    return state.login;
  });

  let dispatch = useDispatch();
  let navigate = useNavigate();

  // 登录提交逻辑
  let fn = async (e) => {
    e.preventDefault();
    try {
      // 调用登录接口
      let res = await request.user.login(email, password);
      // 触发 loginSubmit action 更新状态
      dispatch(loginSubmit(res));
      if (res.status === 1) {
        // 登录成功跳转到首页
        navigate("/");
      }
    } catch (error) {
      console.log(error);
      // 系统错误时触发 loginSubmit 更新错误信息
      dispatch(loginSubmit("系统错误 请联系管理员"));
    }
  };

  // 组件卸载时触发 onUnload action 重置登录状态
  useEffect(() => {
    return () => {
      dispatch(onUnload());
    };
  }, []);

  return (
    <div className="container page">
      <div className="row">
        <div className="col-md-6 offset-md-3 col-xs-12">
          <h1>登录</h1>
          <p className="text-xs-center">
            <Link to="/regist">没有账号去往注册页面</Link>
          </p>
          <Errors errors={errors} />
          <form onSubmit={fn}>
            <fieldset className="form-group">
              <input
                type="text"
                className="form-control form-control-lg"
                placeholder="用户邮箱"
                value={email}
                onChange={(e) => {
                  // 更新 email 字段
                  dispatch(
                    loginFileUpdate({ key: "email", value: e.target.value })
                  );
                }}
              />
            </fieldset>
            <fieldset className="form-group">
              <input
                type="password"
                className="form-control form-control-lg"
                placeholder="用户密码"
                value={password}
                onChange={(e) => {
                  // 更新 password 字段
                  dispatch(
                    loginFileUpdate({ key: "password", value: e.target.value })
                  );
                }}
              />
            </fieldset>
            <Button
              htmlType="submit"
              size="large"
              color="primary"
              variant="outlined"
            >
              登录
            </Button>
          </form>
        </div>
      </div>
    </div>
  );
};

// 使用 memo 优化，避免不必要的重渲染
export default memo(Login);
